package org.jflame.commons.excel.handler;

import org.jflame.commons.excel.ExcelAccessException;
import org.jflame.commons.excel.ExcelColumnProperty;
import org.jflame.commons.excel.ExcelConvertUtils;
import org.jflame.commons.util.CollectionHelper;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;

/**
 * excel单行数据与实体bean转换处理器.
 * 
 * @author charles.zhang
 */
public class EntityRowWriter<T> implements IExcelRowWriter<T> {

    private Cell currentCell = null;
    private Object currentValue;
    private final List<ExcelColumnProperty> columnProperties;

    /**
     * 构造函数
     * 
     * @param columnProperties ExcelColumnProperty集合
     */
    public EntityRowWriter(List<ExcelColumnProperty> columnProperties) {
        if (CollectionHelper.isEmpty(columnProperties)) {
            throw new ExcelAccessException("columnPropertys must not be empty");
        }
        this.columnProperties = columnProperties;
    }

    @Override
    public void fillRow(T rowData, Row excelSheetRow, int startColIndex, CellStyle defaultCellStyle) {
        if (rowData == null) {
            return;
        }
        ExcelColumnProperty currentProperty;
        try {
            for (int cellIndex = 0; cellIndex < columnProperties.size(); cellIndex++) {
                currentCell = excelSheetRow.createCell(startColIndex + cellIndex);
                currentProperty = columnProperties.get(cellIndex);
                currentValue = currentProperty.getPropertyDescriptor()
                        .getReadMethod()
                        .invoke(rowData);
                if (currentValue == null || StringUtils.EMPTY.equals(currentValue)) {
                    currentCell.setBlank();
                    continue;
                }

                currentCell.setCellStyle(
                        currentProperty.getColumnStyle() != null ? currentProperty.getColumnStyle() : defaultCellStyle);

                if (setCellRawValue(currentCell, currentValue, currentProperty)) {
                    continue;
                }

                currentCell.setCellValue(ExcelConvertUtils.convertToCellValue(currentProperty, currentValue));
            }
        } catch (Exception e) {
            throw new ExcelAccessException(e);
        }
    }

    public List<ExcelColumnProperty> getColumnPropertys() {
        return columnProperties;
    }

}
